// ajax引入
import ajax from './ajax.js'
if (!localStorage.getItem('article_list')) {
    ajax({
        url: 'https://api.iynn.cn/mock?t=2',
    }).then(res => {
        localStorage.setItem('article_list', JSON.stringify(res.data))
    })
}
let dataArr = JSON.parse(localStorage.getItem('article_list'))
render(dataArr)

// 渲染函数
function render(arr) {
    let str = ''
    arr.forEach(item=> {
    str += ` <tr>
                <td>${item.id}</td>
                <td>${item.title}</td>
                <td>${item.user}</td>
                <td>${item.date}</td>
                <td>
                    <button type="button" class="btn btn-danger" id="${item.id}">删除</button>
                    <button type="button" class="btn btn-primary" id="${item.id}">编辑</button> 
                </td>
            </tr>`
    });
    document.querySelector('tbody').innerHTML = str
}

// 新增
add.onclick = () =>{
    dataArr.push({
        'id':dataArr[dataArr.length - 1].id*1+1,
        'title':hero.value,
        'user':ren.value,
        'date':riqi.value
    })
    localStorage.setItem('article_list',JSON.stringify(dataArr))
    render(dataArr)
}

// 事件委托
document.querySelector('tbody').onclick = (e) =>{
    // 删除
    if (e.target.innerHTML == '删除') {
        dataArr.forEach((item,index)=>{
            if(item.id == e.target.id){
                dataArr.splice(index, 1)
            }
        })
        // 重排数据id
        dataArr.forEach((item1,index)=>{
            item1.id = index+1 
        })  
        render(dataArr)
        localStorage.setItem('article_list',JSON.stringify(dataArr))
    }

    // 编辑
    if (e.target.innerHTML == '编辑') {
        $('#myModal').modal('show')
        let initObj = dataArr.find((item)=>{
            return item.id == e.target.id
        })
        addHero.value = initObj.title
        addRen.value = initObj.user
        addRiqi.value = initObj.date.replaceAll('/','-')
        addSure.onclick = ()=>{
            $('#myModal').modal('hide')
            dataArr.forEach(item=>{
                if (item.id == e.target.id) {
                    item.title = addHero.value
                    item.user = addRen.value
                    item.date = addRiqi.value
                }
            })
            localStorage.setItem('article_list',JSON.stringify(dataArr))
            render(dataArr)
        }
        close1.onclick = ()=>{
            $('#myModal').modal('hide')
        }
    }
} 
 
